#This script builds edisonclient for Ubuntu and edisonserver for Yocto. 

#Client build for Ubuntu
#Set IOTIVITY_ROOT to the root of oic-resource on Ubuntu.
IOTIVITY_ROOT = '' 
#Set IOTIVITY_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, liboc_logger.so and libcoap.so.               
IOTIVITY_LIBS_PATH = ''

env = DefaultEnvironment()
env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
env.AppendUnique(LINKFLAGS = ['-pthread'])
env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap'])

#Server build
envServer = env.Clone()
'''
This code injects Yocto cross-compilation flags into scons' default environment
in order to invoke the relevant tools while performing a build.
'''
import os.path, re
sdk_root = ''
try:
    CC = os.environ['CC']
    sdk_root = re.search(r'--sysroot=\S+', CC).group().split('=')[1]
    target_prefix = CC.split()[0]
    target_prefix = target_prefix[:len(target_prefix)-3]
    tools = {"CC" : target_prefix+"gcc",
             "CXX" : target_prefix+"g++",
             "AS" : target_prefix+"as",
             "LD" : target_prefix+"ld",
             "GDB" : target_prefix+"gdb",
             "STRIP" : target_prefix+"strip",
             "RANLIB" : target_prefix+"ranlib",
             "OBJCOPY" : target_prefix+"objcopy",
             "OBJDUMP" : target_prefix+"objdump",
             "AR" : target_prefix+"ar",
             "NM" : target_prefix+"nm",
             "M4" : "m4",
             "STRINGS": target_prefix+"strings"}
    PATH = os.environ['PATH'].split(os.pathsep)
    for tool in tools:
        if tool in os.environ:
            for path in PATH:
	            if os.path.isfile(os.path.join(path, tools[tool])):
	                envServer[tool] = os.path.join(path, os.environ[tool])
    envServer.Program('switch', ['client.cpp', 'observer.cpp'])
    envServer.AppendUnique(LIBS = ['mraa'])
    envServer.AppendUnique(CPPPATH = [
                sdk_root + '/usr/include/iotivity/',
                sdk_root + '/usr/include/iotivity/stack/',
                sdk_root + '/usr/include/iotivity/ocsocket/',
                sdk_root + '/usr/include/iotivity/oc_logger/',
                ])	                
except:
    print "ERROR configuring Yocto cross-toolchain environment. This is required for building the server"
